<template>
	<!-- 把这个容器做成富文本框 -->
	<div class="container">
		<div class="plugins-tips">
			<h3>编辑文章</h3>
			<!-- <a href="https://www.wangeditor.com/doc/" target="_blank">wangEditor</a> -->
		</div>
		<div class="mgb20" ref="editor"></div>
		<!-- <el-button type="primary" @click="syncHTML">提交</el-button> -->
	</div>
</template>

<script setup lang="ts" name="editor">
// 文档地址：https://www.wangeditor.com/v4/
import WangEditor from 'wangeditor'
import { ref, reactive, onMounted, onBeforeUnmount , onUnmounted, watch} from 'vue'
import { useArticleStore } from '../store/article'

import { HOST_URL } from '../config/host'
// 记录处理图片的接口地址
const options = reactive({upload: `${HOST_URL}/photo/upload`})

// 创建文章状态管理对象
let articleStore = useArticleStore()
const editor = ref(null);

// watch(articleStore,()=>{
// 	if(articleStore.$state.html == ""){
// 		console.log('test11111')
// 		content.html = "";
// 	}
// })
// 创建WangEditor的实例
let instance: any;

onMounted(() => {
	// WangEditor的实例
	instance = new WangEditor(editor.value);
	instance.config.zIndex = 1;
	// 配置上传图片的参数
	instance.config.uploadImgServer = options.upload;
	//配置上传参数
	instance.config.uploadFileName = 'photo'
	// 获取token
	let token = localStorage.getItem('AUTO_TOKEN')
	// 配置提交的参数
	instance.config.uploadImgParams = { token }

	// 编辑区域 focus（聚焦）和 blur（失焦）时触发的回调函数。
	// instance.config.onfocus = function (newHtml: string) {
	// 	console.log('onfocus', newHtml) // 获取最新的 html 内容
	// }
	// instance.onblur = function (newHtml: string) {
	// 	console.log('onblur', newHtml) // 获取最新的 html 内容
	// }
	// 配置 onchange 回调函数
	instance.config.onchange = function (newHtml: string) {
		// console.log("change:", newHtml);
		// 调用pinia提供API 储存数据
		articleStore.changeHtml(newHtml);
	};
	// 配置触发 onchange 的时间频率，默认为 200ms
	instance.config.onchangeTimeout = 2000; // 修改为 500ms
	

	instance.create();
});

onUnmounted(()=>{
	instance.destroy();
	instance = null;
	editor.value = null
})


// const syncHTML = () => {
// 	content.html = instance.txt.html();
// 	console.log(content.html);
// };
</script>

<style>

img {
	max-width: 1000px;
	width: 100%;
}
</style>
